/**
 * Created by Kpeng on 2017/7/10.
 * Depending on the jquery-1.11.3.min.js.
 * Depending on the style.css.
 * To cite this document, always state the source as shown above.
 */

//SKU配置

$(function () {
  wzERP.SkuConfig.init();
});

//
wzERP.SkuConfig.init = function () {
  wzERP.SkuConfig.addHandle();
  wzERP.SkuConfig.turnPage();//分页
  wzERP.SkuConfig.viewHandle();
  wzERP.SkuConfig.editHandle();
  wzERP.SkuConfig.delHandle();
  wzERP.SkuConfig.changeScLevels("serviceClassQuery");
};

//分页跳转
wzERP.SkuConfig.turnPage = function () {
  var opt = {
    pageUrl: $("#skuSetPageUrl").val(),
    pageSearch: "#filterForm",
    pagesTotal: parseInt($('#pages').val()),
    pageCurr: parseInt($('#current').val()),
    pageSize: parseInt($('#pageSize').val()),
    currId: "#current"
  };
  wzERP.Common.pagingHandle(opt);
};

//
function search() {
  $("#current").val(1);
  $("#filterForm").action = "/basedata/erpSkuDetail/queryPage";
  $("#filterForm").submit();
}

//查看服务
wzERP.SkuConfig.viewHandle = function () {
  var opt = {
    ele: '.viewBtn',
    modalBox: '#modal',
    modalTitleStr: '查看SKU',
    snippets: $("#skuUpdateUrlPage").val(),
    callback: function () {
      wzERP.SkuConfig.cb(this);
    }
  };
  wzERP.Common.handleData(opt);
};

//添加弹窗
wzERP.SkuConfig.addHandle = function () {
  var opt = {
    ele: '.addBtn',
    modalBox: '#modal',
    modalTitleStr: '添加SKU',
    snippets: $("#skuUpdateUrlPage").val(),
    callback: function () {
      //添加弹窗要清除确认按钮的id
      $('#saveSkuBtn').removeAttr('data-id');
      //
      wzERP.SkuConfig.cb(this);
    }
  };
  wzERP.SkuConfig.handleData(opt);
};

//编辑服务
wzERP.SkuConfig.editHandle = function () {
  var opt = {
    ele: '.editBtn',
    modalBox: '#modal',
    modalTitleStr: '编辑SKU',
    snippets: $("#skuUpdateUrlPage").val(),
    onApprove: function () {
      wzERP.Common.saveHandle('#skuSetForm', '#skuUpdate',
          $(this).find('.setId'), wzERP.Common.delayReload(wzERP.delayTime));
    },
    callback: function () {
      wzERP.SkuConfig.cb(this);
    }
  };
  wzERP.SkuConfig.handleData(opt);
};

//删除操作
wzERP.SkuConfig.delHandle = function () {
  /*var opt = {
   ele: '.delBtn',
   modalBox: '#modal',
   modalTitleStr: '',
   onApprove: function () {
   wzERP.Common.deleteData('#skuDelete', $(this).find('.setId'));
   },
   snippets: $("#skuDelepageUrl").val(),
   callback: function () {
   wzERP.SkuConfig.cb(this);
   }
   };
   wzERP.Common.handleData(opt);*/

  $('#main').on('click', '.delBtn', function () {
    var $self = $(this);
    layer.alert('确定删除该SKU吗？', {
          title: '提示信息',
          btn: ['取消', '确认'],
          btn1: function (index) {
            layer.close(index)
          },
          btn2: function () {
            wzERP.Common.deleteData('#skuDelete', $self)
          }
        }
    );
  })
};

//操作SKU服务
var hasClick = false;
wzERP.SkuConfig.addService = function () {
  var modal = $('#modal'),
      selects = modal.find('select').parent(),
      opt = {
        addBtn: '.addSkuBtn',
        container: ".table-edit",
        saveBtn: "#saveSkuBtn",
        delBtn: ".delSkuBtn",
        reserved: 1,
        submitForm: "#skuAddList",
        delFn: function () {
          var orgOfficial = $("#skuAddList").find(
              "[name='officialExpenses']")[0].defaultValue;
          var checkeds = $("#tableList").find('[type="checkbox"]:checked');
          if (null == orgOfficial || '' == orgOfficial) {
            checkeds.each(function (i, obj) {
              $(obj).parent().parent().parent().remove();
            });
            return;
          }
          else {
            var delDBDataFlag = false;
            var selIds = this.ids.ids,
                len = selIds.length,
                i = 0,
                id;
            $(selIds).each(function (i, id) {
              if (id.id == undefined) {
                var trs = $(
                    $("#tableList").find('[type="checkbox"]:checked')).parents(
                    'tr').not('data-id');
                $(trs).remove();
              }
              else {
                delDBDataFlag = true;
              }
            });
            if (delDBDataFlag) {
              var ajaxData = {
                param: this.ids,
                url: '#deleteAll'
              };
              wzERP.Common.saveAjaxHandle(ajaxData);
            }
          }
        },
        saveFn: function () {
          //表单不符合要求返回

          if (!!wzERP.SkuConfig.checkform('#skuAddList')
              || !!wzERP.SkuConfig.checkform('#detailList tbody tr')) {
            return false;
          }
          if (hasClick) {
            return false;
          }
          hasClick = true;
          $("#saveSkuBtn").attr("disabled", true);
          var isAbled = $("button[id^='saveSkuBtn']").prop("disabled");
          console.info(isAbled)
          // console.info("add点击次数："+addCount);
          var rows = modal.find('.row-item'),
              childList = [],
              serviceId = 0,
              arr = [$("#serviceClass").find("#scLevel1").val(),
                $("#serviceClass").find("#scLevel2").val(),
                $("#serviceClass").find("#scLevel3").val()];
          for (var i = 0, len = arr.length; i < len; i++) {
            if (arr[i]) {
              serviceId = arr[i]
            }
          }

          rows.each(function () {
            childList.push({
              id: $(this).data('id'),//自身ID
              skuName: $(this).find('input[name=skuName]').val(),//SKU名称
              serviceType: $(this).find('input[name=serviceType]').val(),//服务类型
              unitPriceCost: $(this).find('input[name=unitPriceCost]').val(),//单价成本
              marketPrice: $(this).find('input[name=marketPrice]').val(),//单价市场价
              additionalCost: $(this).find('input[name=additionalCost]').val(),//附加成本
              additionalMarketPrice: $(this).find(
                  'input[name=additionalMarketPrice]').val(),//附加市场价
              maxDiscRate: $(this).find('input[name=maxDiscRate]').val(),//最高折扣率
              originalPrice: $(this).find('.originalPrice').text(),//原价
              minPrice: $(this).find('.minPrice').text(),//最低价
              costPrice: $(this).find('input[name=costPrice]').val()//成交价
            });
          });

          var param = {
                id: $("#saveSkuBtn").data('id'),  //父级ID
                serviceClassifiId: serviceId,  //服务分类
                businessId: modal.find('select[name=businessId]').val(),//业务名称
                type: modal.find('input[name=type]').val(),//类型
                property: modal.find('input[name=property]').val(),//属性
                officialExpenses: modal.find('input[name=officialExpenses]').val(),//官费
                additionalOfficialExpenses: modal.find(
                    'input[name=additionalOfficialExpenses]').val(),//附加官费
                unit: modal.find('.unit').text(),//单位
                skuDetailList: childList//子列表
              },

              ajaxData = {
                param: param,
                //根据按钮的data-id来区别URL
                url: $(this.saveBtn).data('id') ? '#skuUpdateURL'
                    : '#addSKUUrl',
                successFn: wzERP.Common.delayReload(wzERP.delayTime)
              };

          wzERP.SkuConfig.saveAjaxHandle(ajaxData);
        }
      };

  // 禁用下拉菜单
  modal.hasClass('view-modal') ? selects.addClass('disabled')
      : selects.removeClass('disabled');  //下拉框禁用

  //编辑SKU中禁用某些便签
  if (modal.hasClass('disabled-four')) {
    var disabledByName = ['scLevel1', 'scLevel2', 'scLevel3', 'businessId',
      'type', 'property'];
    for (var i = 0; i < disabledByName.length; i++) {
      console.log(modal.find('[name="' + disabledByName[i] + '"]'))
      modal.find('[name="' + disabledByName[i] + '"]').parent('.ui').addClass(
          'disabled')
    }
  }

  wzERP.SkuConfig.editCheckTable(opt);
};

//按钮触发回调
wzERP.SkuConfig.cb = function (_obj) {
  var modal = $('#modal'),
      saveSkuBtn = $('#saveSkuBtn');
  switch (_obj.ele) {
    case '.delBtn': //删除
      modal.removeClass('fullscreen view-modal disabled-four').addClass(
          'small');
      saveSkuBtn.removeAttr('id').addClass('positive');
      break;
    case '.viewBtn'://查看
      modal.removeClass('small disabled-four').addClass(
          'fullscreen view-modal');
      saveSkuBtn.attr('id', 'saveSkuBtn').removeClass('positive');
      break;
    case '.editBtn'://编辑
      modal.removeClass('small view-modal').addClass(
          'fullscreen disabled-four');
      saveSkuBtn.find(".green").attr('id', 'saveSkuBtn').removeClass('positive')
      break;
    default://其它
      modal.removeClass('small view-modal disabled-four').addClass(
          'fullscreen');
      saveSkuBtn.find(".green").attr('id', 'saveSkuBtn').removeClass('positive')
  }
};

//计算原价
wzERP.SkuConfig.countOriginalPrice = function (_ele) {

  var official = $('#official'), //官费
      original = 0,
      officialPrice,
      costingPrice = 0,  //单价成本
      marketPrice = 0,  //单价市场价
      maxDiscRate = 0,// 折扣
      minPrice = 0, //最低价
      tmp = 0;

  //原价 = 官费 +单价成本 +单价市场价
  // 最低价  = 原价*(1-折扣率)

  //官费触发计算
  $(_ele).on('keyup change blur input propertychange', '#official',
      function () {
        var rows = $('.row-item');//
        officialPrice = parseInt($(this).val() || 0);
        //遍历原价
        rows.find('.originalPrice').each(function () {
          var curRow = $(this).parents('tr');
          costingPrice = parseInt(curRow.find('.costing').val()) || 0; //单价成本
          marketPrice = parseInt(curRow.find('.market').val()) || 0; //市场价
          maxDiscRate = parseInt(curRow.find('.maxDiscRate').val()) || 0; //折扣率
          tmp = officialPrice + costingPrice + marketPrice;
          minPrice = tmp * (100 - maxDiscRate) / 100;
          $(this).text(tmp);
          curRow.find('.minPrice').text(minPrice)
        });
      });

  // 单价成本触发
  $(_ele).on('keyup change blur input propertychange', '.costing', function () {
    countOrigin(this);
  });

  // 单价市场价触发
  $(_ele).on('keyup change blur input propertychange', '.market', function () {
    countOrigin(this);
  });

  // 折扣率触发
  $(_ele).on('keyup input propertychange', '.maxDiscRate', function (ev) {
    var curRow = $(this).parents('tr');  //当前行
    var originalPrice = parseInt(curRow.find('.originalPrice').text())  //原价
    maxDiscRate = parseInt($(this).val()) || 0;//折扣
    var reg = /^(100|[0-9]{0,2})$/;
    var val = $(this).val();
    if (val == '') {
      return;
    }
    if (!reg.test(val)) {
      maxDiscRate = 0;
      $(this).val('');
    }
    else {
      $(this).val(parseInt($(this).val(), 10));
    }
    // if (!(ev.keyCode >= 48 && ev.keyCode <= 57 ) &&  !(ev.keyCode >= 96 && ev.keyCode <= 105 ) ) {
    //     maxDiscRate = 0;
    //     $(this).val('')
    // }
    minPrice = originalPrice * (100 - maxDiscRate) / 100;
    curRow.find('.minPrice').text(minPrice)
  });

  //单价或者市场价触发
  function countOrigin(_obj) {
    var curRow = $(_obj).parents('tr');
    original = curRow.find('.originalPrice');  //原价
    marketPrice = parseInt(curRow.find('.market').val()) || 0; //单价成本
    costingPrice = parseInt(curRow.find('.costing').val()) || 0; //市场价
    maxDiscRate = parseInt(curRow.find('.maxDiscRate').val()) || 0; //折扣率
    officialPrice = parseInt($('#official').val()) || 0; //官费
    tmp = officialPrice + costingPrice + marketPrice;
    minPrice = tmp * (100 - maxDiscRate) / 100;
    original.text(tmp);
    curRow.find('.minPrice').text(minPrice)
  }
};

//服务分类三级联动
wzERP.SkuConfig.changeScLevels = function (id) {
  var scLevel1 = $("#" + id).find('#scLevel1'),
      scLevel2 = $("#" + id).find('#scLevel2'),
      scLevel3 = $("#" + id).find('#scLevel3'),
      busiName = $("#" + id).find('#busiName'),
      getNextLeverList = $('#getNextLeverList').val(),//获取二级列表接口
      getBusiNameList = $('#getBusiNameList').val(),//获取业务名称接口
      recData = {};//接收的参数

  if (!scLevel2.val()) {
    scLevel2.parent().hide();  //二级三级初始化
  }
  if (!scLevel3.val()) {
    scLevel3.parent().hide();  //二级三级初始化
  }

  // 一级服务分类下拉事件
  scLevel1.on('change', function () {
    var param = {"parentId": $(this).val()};
    scLevel2.dropdown('clear');
    scLevel3.dropdown('clear');
    busiName.dropdown('clear');
    scLevel2.parent().hide();
    scLevel3.parent().hide();

    //渲染二级
    $.post(getNextLeverList, param, function (data) {
      var temp = '<option value=""></option>';//字符串拼接
      recData = data.data;
      if (recData.length) {
        $.each(recData, function () {
          var name = this.classificationName,
              thisVal = this.id;
          temp += '<option value=' + thisVal + '>' + name + '</option>'
        });

        scLevel2.empty().append(temp).parent().show();
        scLevel3.parent().hide();
      } else {
        scLevel2.parent().hide();
        scLevel3.parent().hide();
      }
    });

    //渲染业务类型
    $.post(getBusiNameList, param, function (data) {
      var temp = '<option value=""></option>';//字符串拼接
      recData = data.data;
      $.each(recData, function () {
        var thisName = this.businessName,
            thisVal = this.id;
        temp += '<option value=' + thisVal + '>' + thisName + '</option>'
      });
      busiName.empty().append(temp);
    });
  });

  //二级服务分类下拉事件
  scLevel2.on('change', function () {
    var param = {"parentId": $(this).val()};
    scLevel3.dropdown('clear');
    scLevel3.parent().hide()

    //渲染三级
    $.post(getNextLeverList, param, function (data) {
      var temp = '<option value=""></option>';
      recData = data.data;
      if (recData.length) {
        $.each(recData, function () {
          var thisName = this.classificationName,
              thisVal = this.id;
          temp += '<option value=' + thisVal + '>' + thisName + '</option>'
        });
        scLevel3.empty().append(temp).parent().show();
      } else {
        scLevel3.parent().hide();
        scLevel3.parent().hide();
      }
    })
  });
};
wzERP.SkuConfig.changeScLev2 = function () {
  var scLevel2 = $('#scLevel2'),
      scLevel3 = $('#scLevel3'),
      busiName = $('#busiName'),
      getNextLeverList = $('#getNextLeverList').val(),//获取二级列表接口
      param = {},
      recData = {};//接收的参数

  // 二级服务分类下拉事件
  scLevel2.on('change', function () {

    param = {"parentId": $(this).val()};

    scLevel3.dropdown('clear').parent().hide();

    $.post(getNextLeverList, param, function (data) {
      var temp = '<option value=""></option>';
      recData = data.data;
      if (recData.length) {
        $.each(recData, function () {
          var thisName = this.classificationName,
              thisVal = this.id;
          temp += '<option value=' + thisVal + '>' + thisName + '</option>'
        });
        // debugger;
        scLevel3.empty().append(temp).parents('.field').show();
      } else {
        scLevel3.parent().hide();
        scLevel3.parent().hide();
      }
    })
  });

};

//下拉
wzERP.SkuConfig.dropdown = function () {
  $('.ui.dropdown').dropdown({
    showOnFocus: false,
    onChange: function (value, text, $selectedItem) {
      $(this).attr('value', value).addClass('required');
      $selectedItem.parents('.dropdown').removeClass('required');
    }
  });
}

//SKU详情表单验证器
wzERP.SkuConfig.verifier = function (_selector) {
  /*Arg Guide
   @_selector: 对象选择器
   */
  $(_selector).form({
    on: 'blur',
    // inline: true,
    transition: 'fade',
    fields: {
      //SKU名称
      skuName: {
        identifier: 'skuName',
        rules: [{
          type: 'empty'
        }, {
          type: 'regExp[/^.{0,20}$/]',
          prompt: '限制20字'
        }]
      },
      //服务类型
      serviceType: {
        identifier: 'serviceType',
        optional: true,
        rules: [{
          type: 'regExp[/^.{0,10}$/]',
          prompt: '限制10字'
        }]
      },
      //单价成本
      unitPriceCost: {
        identifier: 'unitPriceCost',
        optional: true,
        rules: [{
          type: 'regExp[/^\\d+(?:\\.\\d{1,2})?$/]',
          prompt: '最多两位有效小数'
        }, {
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      },
      //单价市场价
      marketPrice: {
        identifier: 'marketPrice',
        rules: [{
          type: 'empty'
        }, {
          type: 'regExp[/^\\d+(?:\\.\\d{1,2})?$/]',
          prompt: '最多两位有效小数'
        }, {
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      },
      //附加成本
      additionalCost: {
        identifier: 'additionalCost',
        optional: true,
        rules: [{
          type: 'regExp[/^\\d+(?:\\.\\d{1,2})?$/]',
          prompt: '最多两位有效小数'
        }, {
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      },
      //附加市场价
      additionalMarketPrice: {
        identifier: 'additionalMarketPrice',
        optional: true,
        rules: [{
          type: 'regExp[/^\\d+(?:\\.\\d{1,2})?$/]',
          prompt: '最多两位有效小数'
        }, {
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      },
      //最高折扣率
      maxDiscRate: {
        identifier: 'maxDiscRate',
        rules: [{
          type: 'empty',
          prompt: '最高折扣率'
        }, {
          type: 'regExp[/^([0-9]|[0-9]\.\d+|[1-9][0-9]|[1-9][0-9]\.\d+|100)$/]',
          prompt: '限0-100'
        }]
      },
      //单价市场价
      costPrice: {
        identifier: 'costPrice',
        rules: [{
          type: 'empty'
        }, {
          type: 'regExp[/^\\d+(?:\\.\\d{1,2})?$/]',
          prompt: '最多两位有效小数'
        }, {
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      },
    }
  });
};

//SKU主表单验证器
wzERP.SkuConfig.verifier1 = function (_selector) {
  /*Arg Guide
   @_selector: 对象选择器
   */
  $(_selector).form({
    on: 'blur',
    // inline: true,
    transition: 'fade',
    fields: {
      //服务分类
      scLevel1: {
        identifier: 'scLevel1',
        rules: [{
          type: 'empty'
        }]
      },
      //服务分类
      scLevel2: {
        identifier: 'scLevel2',
        rules: [{
          type: 'empty'
        }]
      },
      //业务名称
      businessId: {
        identifier: 'businessId',
        rules: [{
          type: 'empty',
          prompt: '请选择业务'
        }]
      },
      //类型
      type: {
        identifier: 'type',
        optional: true,
        rules: [{
          type: 'regExp[/^.{0,20}$/]'
        }]
      },
      //属性
      property: {
        identifier: 'property',
        optional: true,
        rules: [{
          type: 'regExp[/^.{0,20}$/]'
        }]
      },
      //官费
      officialExpenses: {
        identifier: 'officialExpenses',
        optional: true,
        rules: [{
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      },
      //附加官费 costPrice
      additionalOfficialExpenses: {
        identifier: 'additionalOfficialExpenses',
        optional: true,
        rules: [{
          type: 'regExp[/^\\d+(?:\\.\\d{1,2})?$/]',
          prompt: '最多两位有效小数'
        }, {
          type: 'regExp[/^\\d{0,10}$/]',
          prompt: '限10位数字'
        }]
      }
    }
  });
};

//表单验证出口
wzERP.SkuConfig.checkform = function (ele) {
  /*Arg Guide
   @ ele 要验证的表单
   */
  var $target = $(ele);
  var hasError = false;
  if ($target.length == 1) {
    $(ele).form('submit');
    hasError = $(ele).hasClass('error');
  } else {
    $(ele).each(function () {
      $(this).form('submit');
      if ($(this).hasClass('error')) {
        hasError = true;
      }
    })
  }
  return hasError;
}

//从common.js提出来
wzERP.SkuConfig.editCheckTable = function (_option) {
  /*Arg Guide
   @ _option.addBtn 添加按钮
   @ _option.tBody tbody装载盒子
   @ _option.template 字符串模版
   @ _option.submitForm 真正提交的Form
   @ _option.saveFn  保存回调
   */

  var submitForm = $(_option.submitForm),
      container = $(_option.container),
      tBody = container.find('tbody'),  //tbody装载盒子
      rows = tBody.find('.row-item'), //所有行
      fields = submitForm.find('.fields'), //仅表单区域
      tempHtml = rows.prop('outerHTML'),// 字符串模版
      curRow = null,
      editings = 0,
      isPass = true, //当前行
      wrapper = _option.wrapper ? $(_option.wrapper) : $('#modalContent');
  //条件验证，检测是否有未填或者不符合规则项
  wzERP.Common.tableVerify = function () {
    var isPrompt = submitForm.find('.prompt').length; //判断是否有未保存必填项
    rows = tBody.find('.row-item'); //刷新行数
    if (rows.length) {
      rows.each(function () {
        verify(this);
      });
    } else if (fields.length) {
      fields.each(function () {
        verify(this);
      })
    }

    function verify(_obj) {
      var requireds = $(_obj).find('.required');
      rows = tBody.find('.row-item'); //所有行
      requireds.each(function () {
        if (!this.value || isPrompt > 0) {  //当表单为空并且有报错
          isPass = false;
          layer.msg('请检查填写内容', {icon: 2});
          return false;
        } else {
          isPass = true;
          requireds = $(this).find('.required');
          return true;
        }
      });
    }
  };

  //是否显示删除按钮
  wzERP.Common.editTable.delIsShow = function () {
    rows = tBody.find('.row-item'); //所有行
    rows.length ? $(_option.delBtn).removeClass('disabled') : $(
        _option.delBtn).addClass('disabled');
  };
  wzERP.Common.editTable.delIsShow();

  //新增一条数据
  if (_option.addBtn) {
    wrapper.off('click').on('click', _option.addBtn, function () {
      wzERP.Common.tableVerify();
      editings = $(this).parents('tbody').find('.editing').length;
      if (isPass && editings === 0) {
        tempHtml = tempHtml.replace(/(<input.*?value=").*?(".*?\/>)/g,
            '$1$2').replace(/data-id=".*?"/g, '');//这里tempHtml需要正则处理一下清空所有input值
        tBody.prepend(tempHtml);
        $(_option.delBtn).show();
        //处理新增加的（第）一行
        var firstRow = tBody.find('.row-item').first();
        firstRow.addClass('editing new').find(_option.saveBtn).removeAttr(
            'data-id');

        if (firstRow.find('select')) {
          //清空下拉框
          tBody.find('.selection').removeClass('required');
          firstRow.find('.selection').removeClass('disabled').dropdown('clear');
          wzERP.Common.dropdown();
        }
        if (firstRow.find('input')) {
          //清空输入框
          firstRow.find('input').val('')
        }
        if (firstRow.find('.custom-text')) {
          //清空输入框
          firstRow.find('.custom-text').val('')
        }
        //SKU明细表单验证器
        wzERP.SkuConfig.verifier("#detailList tr");
      }
    });
  }

  //保存
  if (_option.saveBtn) {
    $(document).on('click', _option.saveBtn, function () {
      wzERP.Common.tableVerify(curRow);
      var checkData = [];
      rows = tBody.find('.row-item'); //重置所有行
      curRow = $(this).parents('tr');  //当前行
      if (isPass) {
        rows.each(function () { //保存id
          checkData.push($(this).data('id'));
        });
        curRow.removeClass('editing');
        if (_option.submitForm) {
          $(_option.submitForm).find('input').each(function () {
            var valText = $(this).siblings('.val');
            valText.text($.trim($(this).val()));
          });
        }

        if (_option.saveFn instanceof Function) {
          _option.saveFn();
        }
      }
    });
  }

  //批量删除数据
  if (_option.delBtn) {
    wrapper.on('click', _option.delBtn, function () {
      var checkbox = tBody.find('.checkbox').not('.toggle'),
          checkeds = tBody.find('input[type=checkbox]:checked'),//选中的项
          noCheckeds = tBody.find('input[type=checkbox]:not(:checked)'),//未选中的项
          reserved = _option.reserved || 0,
          checkedIds = [],
          checkedData = [];
      _option.ids = '';   //初始化及清空删除ID
      if (checkeds.length) {
        if (reserved && noCheckeds.length < reserved) {
          layer.msg('请至少保留' + reserved + '条数据', {icon: 7});
          return false;
        }
        checkeds.each(function () { //保存id
          checkedIds.push($(this).parents('tr').data('id'));
        });
        checkedIds.forEach(function (i) {
          checkedData.push({'id': i})
        })

        layer.confirm('您确定要删除该数据？',
            {
              title: '提示信息',
              btn: ['取消', '确定'] //按钮
            },
            //取消事件
            function (index) {
              layer.close(index);
            },
            function () {
              _option.ids = {'ids': checkedData};//值格式
              if (_option.delFn instanceof Function) {
                _option.delFn();
              }
            });
      } else {
        layer.msg('请勾选需要删除的项', {icon: 3});
        return false;
      }
      wzERP.Common.editTable.delIsShow();
    });
  }
};

//提交ajax按需提交操作
wzERP.SkuConfig.saveAjaxHandle = function (_obj) {
  /*Arg Guide
   @ _obj.formdata:提交form的ID
   @ _obj.url:接口地址
   @ _obj.extendObj: 继承对象
   @ _obj.successFn  成功处理回调
   @ _obj.errorFn  错误处理回调
   */
  $("#saveSkuBtn").attr("disabled", true);
  var isAbled = $("button[id^='saveSkuBtn']").prop("disabled");
  console.info(isAbled)
  var param = _obj.param, //json数据
      submitUrl = $(_obj.url).val();//接口地址
  if (Array.isArray(_obj.extendObj)) {
    param = $.extend(param, _obj.extendObj);
  }
  console.log(JSON.stringify(param));
  $.ajax({
    type: "POST",
    url: submitUrl,
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify(param),
    success: function (data) {
      var resData = data.data;
      if (resData) {
        _obj.newId = resData.id;
      }
      switch (data.code) {
        case 0://成功
          layer.msg(data.msg, {icon: 7});
          if (_obj.successFn instanceof Function) {
            _obj.successFn();
          }
          break;
        case 1: //失败
          layer.msg(data.msg, {icon: 5});
          if (_obj.errorFn instanceof Function) {
            _obj.errorFn();
          }
          break;
        default: //默认
          layer.msg(data.msg, {icon: 2});
          if (_obj.errorFn instanceof Function) {
            _obj.errorFn();
          }
      }
    }
  });
};

//模态框响应
wzERP.SkuConfig.handleData = function (_option) {
  /*Arg Guide
   @ option.ele:触发元素
   @ option.modal:模态框元素
   @ option.onApprove:“保存/确定”事件函数
   @ option.snippets:模态框内容代码片段路由
   @ option.callback:回调函数
   */
  $('#main').on('click', _option.ele, function () {
    var btnType = $(this).data('type'),  //获取挂载
        modalBox = $(_option.modalBox),
        modalHeader = modalBox.find('.header'),
        isDelete = btnType === 'delete',
        isAdd = btnType === 'add',
        getId = $(this).data('id') || ""; //获取ID ;
    //更改模态框类型
    isDelete ? modalBox.addClass('basic') : modalBox.removeClass('basic');
    _option.event = $(this);
    //将触发按钮的id绑定到模态框确定按钮上
    if (getId) {
      modalBox.find('.setId').attr('data-id', isAdd ? '' : getId);
    }
    modalBox.modal({
      closable: false,
      transition: 'fade',
      onDeny: function () {
        // 拒绝或取消
        //alert('拒绝了拒绝了拒绝了拒绝了!');
      },
      onHidden: function () {
        //关闭模态框
        $('#modal').removeAttr('style');
      },
      onApprove: function () {
        var isPass = true,
            requiredHooks = modalBox.find('.required-hook');

        //把required-hook置对
        requiredHooks.each(function () {
          if ($(this)[0].nodeName === 'DIV') {
            $(this).removeClass('required-hook');
            $(this).find('select').addClass('required-hook');
          }
        })
        requiredHooks = modalBox.find('.required-hook');

        //验证必填项是否符合规则
        requiredHooks.each(function () {
          var _this = $(this),
              isPrompt = _this.siblings('.prompt').length; //判断是否有未保存必填项

          console.log(this.value, this.nodeName, $(this).attr('id'));
          var id = $(this).attr('id');
          if (!this.value || isPrompt) {  //当表单为空并且有报错
            if (id == 'addCmpAddPage' || id == 'addDepartAddPage' || id
                == 'addJobAddPage') { //排除兼岗位置不通过问题
              isPass = true;
              if (this.nodeName === 'SELECT') {
                _this.parent('.dropdown').removeClass('error');
              }
              return true;
            }
            isPass = false;
            if (this.nodeName === 'SELECT') {
              _this.parent('.dropdown').addClass('error');
            } else {
              _this.parent('.required').addClass('error');
            }
            if (!this.value) {
              debugger
              layer.msg('必选项不能留空白', {icon: 2});
              return false;
            }
            layer.msg('填写项不符合规则', {icon: 2});
            return false;
          } else {
            isPass = true;
            if (this.nodeName === 'SELECT') {
              _this.parent('.dropdown').removeClass('error');
            }
            return true;
          }
        });
        if (isPass && _option.onApprove instanceof Function) {
          var flag = _option.onApprove();
          if (flag === false) {
            return false;
          }
          else {
            //console.info("option.onApprove()="+flag);
          }
        } else {
          return false;
        }
      }
    }).modal('show');

    modalHeader.empty().prepend(
        '<i class="warning circle icon red"></i><span>' + _option.modalTitleStr
        + '</span>');
    isDelete ? modalHeader.addClass('del-modal-header')
        : modalHeader.removeClass('del-modal-header');
    if (_option.callback instanceof Function) {
      _option.callback();
    }
    if (_option.url) {
      _option.snippets = _option.url;
      console.log(_option.url);
    }
    wzERP.Common.loadHtml(wzERP.ViewDir + _option.snippets + "?id=" + getId,
        '#modalContent');
    console.log(wzERP.ViewDir + _option.snippets + "?id=" + getId)
  });
};
